package com.gcstorage.tvdev.util;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gcstorage.tvdev.net.HttpResult;
import com.gcstorage.tvdev.net.ParameterizedTypeImpl;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xu on 2019-10-29 13:48
 */
public class GsonUtils {

    public static <T> HttpResult<T> covertObject(JsonElement jsonElement, Class<T> clazz) {
        Type type = new ParameterizedTypeImpl(HttpResult.class, new Class[]{clazz});
        HttpResult<T> result;
        try {
            result = new Gson().fromJson(jsonElement, type);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
            ToastUtils.showShort("转化数据出现错误,请联系管理员");
            result = new HttpResult<>();
        }
        return result;
    }

    public static <T> HttpResult<List<T>> covertArray(JsonElement jsonElement, Class<T> clazz) {
        Type listType = new ParameterizedTypeImpl(List.class, new Class[]{clazz});
        Type type = new ParameterizedTypeImpl(HttpResult.class, new Type[]{listType});
        HttpResult<List<T>> result;
        try {
            result = new Gson().fromJson(jsonElement, type);
        } catch (Exception e) {
            ToastUtils.showShort("转化数据出现错误,请联系管理员");
            result = new HttpResult<>();
        }
        return result;
    }

    public static <T> List<T> toList(String jsonStr, Class<T> clazz) {
        return new Gson().fromJson(jsonStr, new ParameterizedTypeImpl(List.class, new Class[]{clazz}));
    }

    public static <T> List<T> jsonToList(String jsonStr, Class<T> clazz) {
        List<T> lst = new ArrayList<>();

        try {
            JsonArray array = new JsonParser().parse(jsonStr).getAsJsonArray();
            for (final JsonElement elem : array) {
                lst.add(new Gson().fromJson(elem, clazz));
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }

        return lst;
    }

    public static <T> String listToJson(List<T> data) {
        Gson gson = new Gson();
        return gson.toJson(data);
    }

    public static <T> T fromJson(String json, Class<T> type) {
        Gson gson = new Gson();
        return gson.fromJson(json, type);
    }

    public static String toJson(Object bean) {
        return new Gson().toJson(bean);
    }

}
